package test05;

import java.util.*;

public class StudentManager {
    private Set<Student> students;

    public StudentManager() {
        this.students = new HashSet<>();
        initializeData(); // 初始化数据
    }

    // 初始化数据：添加至少5名学生
    private void initializeData() {
        students.add(new Student(1001, "张三", 18, 85));
        students.add(new Student(1002, "李四", 19, 92));
        students.add(new Student(1003, "王五", 17, 78));
        students.add(new Student(1004, "赵六", 20, 95));
        students.add(new Student(1005, "孙七", 18, 88));
    }

    // 1. 查询所有学生信息
    public void showAllStudents() {
        System.out.println("=== 所有学生信息 ===");
        for (Student s : students) {
            System.out.println(s);
        }
    }

    // 2. 添加学生
    public void addStudent(Student student) {
        if (student != null && !students.contains(student)) {
            students.add(student);
            System.out.println("添加成功：" + student.getName());
        } else {
            System.out.println("学生已存在或输入无效！");
        }
    }

    // 3. 删除学生（按编号）
    public void deleteStudent(String id) {
        Student toRemove = null;
        for (Student s : students) {
            if (s.getId().equals(id)) {
                toRemove = s;
                break;
            }
        }
        if (toRemove != null) {
            students.remove(toRemove);
            System.out.println("删除成功：" + toRemove.getName());
        } else {
            System.out.println("未找到编号为 " + id + " 的学生！");
        }
    }

    // 4. 修改学生成绩（按编号）
    public void updateScore(Integer id, int newScore) {
        for (Student s : students) {
            if (s.getId().equals(id)) {
                s.setScore(newScore);
                System.out.println("成绩更新成功！" + s.getName() + " 新成绩：" + newScore);
                return;
            }
        }
        System.out.println("未找到编号为 " + id + " 的学生！");
    }

    // 5. 按年龄从小到大排序并输出
    public void sortAndPrintByAge() {
        List<Student> sortedList = new ArrayList<>(students);
        sortedList.sort(Comparator.comparingInt(Student::getAge));
        System.out.println("\n=== 按年龄从小到大排序 ===");
        sortedList.forEach(System.out::println);
    }

    // 6. 按成绩从高到低排序并输出
    public void sortAndPrintByScore() {
        List<Student> sortedList = new ArrayList<>(students);
        sortedList.sort((a, b) -> Double.compare(b.getScore(), a.getScore()));
        System.out.println("\n=== 按成绩从高到低排序 ===");
        sortedList.forEach(System.out::println);
    }

    // 可选：查找学生（按编号）
    public Student findStudentById(String id) {
        for (Student s : students) {
            if (s.getId().equals(id)) {
                return s;
            }
        }
        return null;
    }
}
